/*
 * Copyright (c) 2024 endless-sky
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "algo_manager_impl.h"
#include "hal_algo.h"
#include "face_best_selector_face_det.h"
#include "common_config_manager.h"
#include <algorithm>
#include <chrono>
#include <thread>
#include <cstring>
#include <nlohmann/json.hpp>
#include <cstdio>
#include <cmath>
#include <vector>

namespace El {
namespace Algo {

// 单例实现
IAlgoManager &IAlgoManager::GetInstance()
{
    static AlgoManagerImpl instance;
    return instance;
}

// 工具函数实现
std::string AlgoTypeToString(AlgoType algoType)
{
    switch (algoType) {
        case ALGO_TYPE_HUMAN_VEHICLE_DET:
            return "human_vehicle_detection";
        case ALGO_TYPE_NON_MOTOR_ELEV_DET:
            return "non_motor_elevator_detection";
        case ALGO_TYPE_FACE_DET:
            return "face_capture";
        case ALGO_TYPE_FACE_RECOGNITION:
            return "face_recognition";
        case ALGO_TYPE_YOLOV8_DET:
            return "yolov8_detection";
        default:
            return "invalid";
    }
}

AlgoType StringToAlgoType(const std::string &str)
{
    if (str == "human_vehicle_detection") {
        return ALGO_TYPE_HUMAN_VEHICLE_DET;
    }
    if (str == "non_motor_elevator_detection") {
        return ALGO_TYPE_NON_MOTOR_ELEV_DET;
    }
    if (str == "face_capture") {
        return ALGO_TYPE_FACE_DET;
    }
    if (str == "face_recognition") {
        return ALGO_TYPE_FACE_RECOGNITION;
    }
    if (str == "yolov8_detection") {
        return ALGO_TYPE_YOLOV8_DET;
    }
    return ALGO_TYPE_INVALID;
}

std::string AlgoStatusToString(AlgoStatus status)
{
    static const std::unordered_map<AlgoStatus, std::string> statusMap = {{AlgoStatus::IDLE, "IDLE"},
                                                                          {AlgoStatus::INITIALIZING, "INITIALIZING"},
                                                                          {AlgoStatus::RUNNING, "RUNNING"},
                                                                          {AlgoStatus::STOPPING, "STOPPING"},
                                                                          {AlgoStatus::ERROR, "ERROR"}};

    auto it = statusMap.find(status);
    if (it != statusMap.end()) {
        return it->second;
    }
    return "unknown";
}

// 静态成员初始化
AlgoManagerImpl *AlgoManagerImpl::instance_ = nullptr;
std::mutex AlgoManagerImpl::instanceMutex_;

AlgoManagerImpl::AlgoManagerImpl()
{
    // 设置单例实例
    std::lock_guard<std::mutex> lock(instanceMutex_);
    instance_ = this;

    EL_INFO("AlgoManagerImpl created");
}

AlgoManagerImpl::~AlgoManagerImpl()
{
    Stop();

    // 清除单例实例
    std::lock_guard<std::mutex> lock(instanceMutex_);
    instance_ = nullptr;

    EL_INFO("AlgoManagerImpl destroyed");
}

bool AlgoManagerImpl::Start()
{
    if (initialized_) {
        EL_WARN("Algo already initialized");
        return true;
    }

    EL_INFO("Starting Algo...");

    // 从配置管理器读取并自动启动算法
    if (!LoadAndStartAlgosFromConfig()) {
        EL_ERROR("Failed to load and start algorithms from config");
        return false;
    }

    // 注册HAL回调
    if (!halCallbackRegistered_) {
        int ret = Hal_Algo_RegisterCallback(OnAlgoResult, nullptr);
        if (ret != 0) {
            EL_ERROR("Failed to register HAL algo callback, ret: {}", ret);
            return false;
        }
        halCallbackRegistered_ = true;
        EL_INFO("HAL algo callback registered successfully");
    }

    initialized_ = true;
    StartResultMonitor();

    // 注册人脸优选事件回调（仅 FACE_CAPTURE 使用）
    FaceBestSelectorFaceDet::GetInstance().SetEventCallback(
        [this](const nlohmann::json &ev) { this->OnFaceBestEvent(ev); });

    // 注册YOLO类别标签配置变更监听
    Common::ConfigManager::GetInstance().Register("/model_manager/yolov8/class_labels",
        [this](const nlohmann::json& newConfig) -> bool {
            EL_INFO("YOLO class labels configuration changed, applying update...");
            UpdateYoloClassLabels(newConfig);
            return true; // 返回true表示处理成功
        });

    EL_INFO("Algo started successfully");
    return true;
}

void AlgoManagerImpl::Stop()
{
    if (!initialized_) {
        return;
    }

    EL_INFO("Stopping Algo...");

    StopResultMonitor();

    // 停止所有算法
    StopAllAlgos();

    // 取消注册HAL回调
    if (halCallbackRegistered_) {
        Hal_Algo_UnregisterCallback();
        halCallbackRegistered_ = false;
    }

    initialized_ = false;
    EL_INFO("Algo stopped");
}

bool AlgoManagerImpl::LoadAndStartAlgosFromConfig()
{
    try {
        // 从配置管理器获取算法配置
        auto config = Common::ConfigManager::GetInstance().GetConfig("/algo_manager");
        if (config.is_null()) {
            EL_WARN("No algo_manager configuration found");
            return true; // 配置不存在不算错误，可能还未初始化
        }

        if (!config.contains("algorithms")) {
            EL_WARN("No algorithms configuration found in algo_manager config");
            return true;
        }

        auto algorithms = config["algorithms"];
        if (!algorithms.is_array()) {
            EL_ERROR("Invalid algorithms configuration format, expected array");
            return false;
        }

        // 遍历算法配置数组并启动
        for (size_t i = 0; i < algorithms.size(); ++i) {
            auto algoConfig = algorithms[i];

            // 检查配置有效性
            if (!algoConfig.contains("type")) {
                EL_WARN("Algorithm config at index {} missing 'type' field, skipping", i);
                continue;
            }

            std::string algoName = algoConfig["type"];

            // 检查是否启用（如果没有enabled字段，默认启用）
            bool enabled = algoConfig.value("enabled", true);

            if (!enabled) {
                EL_INFO("Algorithm {} is disabled, skipping", algoName);
                continue;
            }

            // 转换算法类型
            AlgoType algoType = StringToAlgoType(algoName);
            if (algoType == ALGO_TYPE_HUMAN_VEHICLE_DET) {
                auto engineIt = algoConfig.find("engine");
                if (engineIt != algoConfig.end() && engineIt->is_string() &&
                    engineIt->get<std::string>() == "custom_yolo") {
                    algoType = ALGO_TYPE_YOLOV8_DET;
                    algoName = AlgoTypeToString(algoType);
                }
            }
            if (algoType == ALGO_TYPE_INVALID) {
                EL_WARN("Unknown algorithm type: {}, skipping", algoName);
                continue;
            }

            // 生成实例ID和配置名称
            std::string configName = algoName + "_" + std::to_string(i);
            std::string instanceId = GenerateInstanceId(algoType, configName);

            // 启动算法实例
            if (StartAlgoInstance(instanceId, algoType, algoConfig)) {
                EL_INFO("Successfully started algorithm instance: {} (type: {}, index: {})", instanceId, algoName, i);
            } else {
                EL_ERROR("Failed to start algorithm instance: {} (type: {}, index: {})", instanceId, algoName, i);
            }
        }

        return true;
    } catch (const std::exception &e) {
        EL_ERROR("Exception occurred while loading algorithms from config: {}", e.what());
        return false;
    }
}

bool AlgoManagerImpl::StartAlgo(AlgoType algoType)
{
    if (algoType == ALGO_TYPE_INVALID) {
        EL_ERROR("Invalid algorithm type");
        return false;
    }

    // 使用默认配置启动第一个算法实例
    std::string algoName = AlgoTypeToString(algoType);
    std::string configName = algoName + "_default";
    std::string instanceId = GenerateInstanceId(algoType, configName);

    // 创建默认配置
    nlohmann::json defaultConfig;
    defaultConfig["type"] = algoName;
    defaultConfig["enabled"] = true;
    // 默认与 VPSS CH2 分辨率保持一致，便于 SDK 内置算法直接处理
    defaultConfig["inputWidth"] = 1024;
    defaultConfig["inputHeight"] = 576;
    defaultConfig["confidenceThreshold"] = 0.5f;

    return StartAlgoInstance(instanceId, algoType, defaultConfig);
}

bool AlgoManagerImpl::StopAlgo(AlgoType algoType)
{
    if (algoType == ALGO_TYPE_INVALID) {
        EL_ERROR("Invalid algorithm type");
        return false;
    }

    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    // 遍历所有实例，停止匹配algoType的实例
    bool found = false;
    bool allSuccess = true;
    for (auto &pair : algoInstances_) {
        auto &instance = pair.second;
        if (instance->algoType == algoType) {
            found = true;

            if (instance->status != AlgoStatus::RUNNING) {
                EL_WARN("Algorithm instance {} is not running", instance->instanceId);
                continue;
            }

            // 停止HAL算法
            instance->status = AlgoStatus::STOPPING;
            HAL_ALGO_CONFIG_S halConfig = {};
            halConfig.enType = algoType;
            int ret = Hal_Algo_Stop(&halConfig);
            if (ret != 0) {
                EL_ERROR("Failed to stop HAL algorithm, instance: {}, type: {}, ret: {}", instance->instanceId,
                         static_cast<int>(algoType), ret);
                instance->status = AlgoStatus::ERROR;
                allSuccess = false;
            } else {
                // 更新状态
                instance->status = AlgoStatus::IDLE;
                EL_INFO("Algorithm instance {} stopped", instance->instanceId);
            }
        }
    }

    if (!found) {
        EL_WARN("No algorithm instances found for type {}", static_cast<int>(algoType));
        return false;
    }

    return allSuccess;
}

bool AlgoManagerImpl::StopAllAlgos()
{
    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    bool allSuccess = true;
    for (auto &pair : algoInstances_) {
        // pair.first is std::string (instanceId), pair.second is std::unique_ptr<AlgoInstance>
        auto &instance = pair.second;
        AlgoType algoType = instance->algoType;

        if (instance->status == AlgoStatus::RUNNING) {
            HAL_ALGO_CONFIG_S halConfig = {};
            halConfig.enType = algoType;
            int ret = Hal_Algo_Stop(&halConfig);
            if (ret != 0) {
                EL_ERROR("Failed to stop HAL algorithm, instance: {}, type: {}, ret: {}", instance->instanceId,
                         static_cast<int>(algoType), ret);
                allSuccess = false;
            } else {
                EL_INFO("Algorithm instance {} stopped", instance->instanceId);
            }
        }
    }

    // 清空实例列表
    algoInstances_.clear();

    EL_INFO("All algorithms stopped");
    return allSuccess;
}

AlgoStatus AlgoManagerImpl::GetAlgoStatus(AlgoType algoType) const
{
    if (algoType == ALGO_TYPE_INVALID) {
        return AlgoStatus::IDLE;
    }

    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    // 遍历所有实例，返回第一个匹配algoType的实例状态
    // 如果有多个实例，可能需要不同的策略来决定返回哪个状态
    for (const auto &pair : algoInstances_) {
        const auto &instance = pair.second;
        if (instance->algoType == algoType) {
            return instance->status;
        }
    }

    return AlgoStatus::IDLE;
}

void AlgoManagerImpl::SetResultCallback(ResultCallback callback)
{
    std::lock_guard<std::mutex> lock(resultCallbackMutex_);
    resultCallback_ = callback;
    EL_INFO("Result callback set");
}

bool AlgoManagerImpl::SetConfidenceThreshold(AlgoType algoType, float threshold)
{
    if (algoType == ALGO_TYPE_INVALID) {
        EL_ERROR("Invalid algorithm type");
        return false;
    }

    if (threshold < 0.0f || threshold > 1.0f) {
        EL_ERROR("Invalid confidence threshold: {}", threshold);
        return false;
    }

    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    bool found = false;
    for (auto &pair : algoInstances_) {
        auto &instance = pair.second;
        if (instance->algoType == algoType) {
            instance->confidenceThreshold = threshold;
            EL_INFO("Set confidence threshold for algorithm instance {}: {}", instance->instanceId, threshold);
            found = true;
        }
    }

    if (!found) {
        EL_ERROR("No algorithm instances found for type {}", static_cast<int>(algoType));
        return false;
    }

    return true;
}

bool AlgoManagerImpl::LoadAlgoConfigFromFile(const std::string &configName,
                                             const nlohmann::json &config,
                                             HAL_ALGO_CONFIG_S &halConfig)
{
    try {
        // 验证配置
        AlgoType algoType = StringToAlgoType(config.value("type", ""));
        if (algoType == ALGO_TYPE_HUMAN_VEHICLE_DET) {
            auto engineIt = config.find("engine");
            if (engineIt != config.end() && engineIt->is_string() && engineIt->get<std::string>() == "custom_yolo") {
                algoType = ALGO_TYPE_YOLOV8_DET;
            }
        }
        if (!ValidateAlgoConfig(algoType, config)) {
            EL_ERROR("Invalid configuration for algorithm: {}", configName);
            return false;
        }

        // 转换为HAL配置
        memset(&halConfig, 0, sizeof(HAL_ALGO_CONFIG_S));

        halConfig.enType = algoType;
        halConfig.u32Width = config.value("inputWidth", 1024);
        halConfig.u32Height = config.value("inputHeight", 576);

        float threshold = config.value("confidenceThreshold", 0.5f);
        if (std::isnan(threshold)) {
            threshold = 0.5f;
        }
        threshold = std::clamp(threshold, 0.0f, 1.0f);
        halConfig.confidenceThreshold = threshold;

        // 根据算法类型在 HAL 层选择具体实现
        // 传递模型路径（如配置存在）
        std::string modelPath = config.value("modelPath", std::string());
        if (!modelPath.empty()) {
            std::snprintf(halConfig.modelPath, sizeof(halConfig.modelPath), "%s", modelPath.c_str());
        } else {
            halConfig.modelPath[0] = '\0';
        }

        return true;

    } catch (const std::exception &e) {
        EL_ERROR("Exception occurred while loading config: {}", e.what());
        return false;
    }
}

bool AlgoManagerImpl::ValidateAlgoConfig(AlgoType algoType, const nlohmann::json &config)
{
    (void)algoType;
    // 基本配置有效性检查
    if (!config.is_object()) {
        EL_ERROR("Algorithm config is not a valid object");
        return false;
    }

    // 验证数值范围
    if (config.contains("confidenceThreshold")) {
        float threshold = config["confidenceThreshold"];
        if (threshold < 0.0f || threshold > 1.0f) {
            EL_ERROR("Invalid confidence threshold: {}", threshold);
            return false;
        }
    }

    if (config.contains("inputWidth")) {
        int width = config["inputWidth"];
        if (width <= 0 || width > 4096) {
            EL_ERROR("Invalid input width: {}", width);
            return false;
        }
    }

    if (config.contains("inputHeight")) {
        int height = config["inputHeight"];
        if (height <= 0 || height > 4096) {
            EL_ERROR("Invalid input height: {}", height);
            return false;
        }
    }

    if (config.contains("maxDetections")) {
        int maxDet = config["maxDetections"];
        if (maxDet <= 0 || maxDet > 1000) {
            EL_ERROR("Invalid max detections: {}", maxDet);
            return false;
        }
    }

    return true;
}

void AlgoManagerImpl::OnAlgoResult(HAL_ALGO_REC_RESULT *result, void *pUserData)
{
    (void)pUserData;
    if (result == nullptr) {
        EL_ERROR("Received null result from HAL");
        return;
    }

    std::lock_guard<std::mutex> lock(instanceMutex_);
    if (instance_ != nullptr) {
        instance_->HandleAlgoResult(*result);
    }
}

void AlgoManagerImpl::HandleAlgoResult(const HAL_ALGO_REC_RESULT &halResult)
{
    // 使用 HAL 返回的类型标记
    AlgoType algoType = static_cast<AlgoType>(halResult.enType);
    uint64_t timestamp = GetCurrentTimeMs();

    nlohmann::json jsonResult;
    jsonResult["algorithm_type"] = static_cast<int>(algoType);
    jsonResult["algorithm_name"] = AlgoTypeToString(algoType);
    jsonResult["timestamp"] = timestamp;
    jsonResult["frame_id"] = 0; // HAL结构体中没有frameId字段
    jsonResult["object_count"] = halResult.obj_num;

    // 转换检测结果数组
    nlohmann::json objectsArray = nlohmann::json::array();
    // 使用启动实例时记录的输入分辨率做归一化（与 VPSS CH2/模型输入一致）
    const float imageWidth = static_cast<float>(algoInputWidth_.load());
    const float imageHeight = static_cast<float>(algoInputHeight_.load());

    const bool isFaceType = (algoType == ALGO_TYPE_FACE_DET || algoType == ALGO_TYPE_FACE_RECOGNITION);
    for (int i = 0; i < halResult.obj_num; ++i) {
        const HAL_REC_PARAM *rec = isFaceType ? &halResult.face_para[i].base : &halResult.obj_para[i];

        nlohmann::json detection;
        // 归一化置信度：从0-100整数转为0-1.0浮点数
        detection["confidence"] = static_cast<float>(rec->confidence) / 100.0f;

        // 归一化坐标到 0-1.0 范围
        float normalizedX = static_cast<float>(rec->box.left) / imageWidth;
        float normalizedY = static_cast<float>(rec->box.top) / imageHeight;
        float normalizedWidth = static_cast<float>(rec->box.width) / imageWidth;
        float normalizedHeight = static_cast<float>(rec->box.height) / imageHeight;

        detection["x"] = normalizedX;
        detection["y"] = normalizedY;
        detection["width"] = normalizedWidth;
        detection["height"] = normalizedHeight;

        float normalizedConfidence = static_cast<float>(rec->confidence) / 100.0f;

        EL_DEBUG(
            "Normalized detection[{}]: confidence={}->{}%, coordinates=[{},{},{},{}] -> [{:.3f},{:.3f},{:.3f},{:.3f}]",
            i, rec->confidence, normalizedConfidence, rec->box.left, rec->box.top, rec->box.width, rec->box.height,
            normalizedX, normalizedY, normalizedWidth, normalizedHeight);

        std::string label = (rec->class_name[0] != '\0') ? std::string(rec->class_name) : std::string("");
        detection["label"] = label;

        // 轨迹信息（若底层提供）
        detection["track_id"] = rec->track_id;
        detection["track_status"] = static_cast<int>(rec->track_status);

        // 透传人脸扩展（仅在人脸类目时有效）
        int faceQuality = 0;
        if (isFaceType) {
            const HAL_FACE_PARAM &fp = halResult.face_para[i];
            faceQuality = static_cast<int>(fp.face_quality);
            detection["face_yaw"] = static_cast<int>(fp.face_yaw);
            detection["face_roll"] = static_cast<int>(fp.face_roll);
            detection["face_pitch"] = static_cast<int>(fp.face_pitch);
            detection["face_mask"] = (fp.face_mask != 0);
        }
        detection["face_quality"] = faceQuality;

        objectsArray.push_back(detection);
    }
    jsonResult["objects"] = objectsArray;

    // 窗口内最佳人脸事件（仅基于 FACE_CAPTURE，无特征）
    {
        nlohmann::json bestEvent;
        bool hasEvent = FaceBestSelectorFaceDet::GetInstance().PushHalResult(
            halResult, static_cast<uint32_t>(algoInputWidth_.load()), static_cast<uint32_t>(algoInputHeight_.load()),
            timestamp, bestEvent);
        if (hasEvent) {
            jsonResult["face_best_event"] = bestEvent;
        }
    }

    bool hasValidBoxes = !objectsArray.empty();
    {
        std::lock_guard<std::mutex> lock(resultStateMutex_);
        lastResultTimestampMs_ = timestamp;
        pendingEmptyNotification_ = hasValidBoxes;
    }

    // 更新统计信息
    totalFrameCount_++;
    totalDetectionCount_ += halResult.obj_num;

    // 调用结果回调
    {
        std::lock_guard<std::mutex> lock(resultCallbackMutex_);
        if (resultCallback_) {
            try {
                resultCallback_(jsonResult);
            } catch (const std::exception &e) {
                EL_ERROR("Exception in result callback: {}", e.what());
            }
        }
    }
}

void AlgoManagerImpl::StartResultMonitor()
{
    if (resultMonitorRunning_) {
        return;
    }

    {
        std::lock_guard<std::mutex> lock(resultStateMutex_);
        pendingEmptyNotification_ = false;
        lastResultTimestampMs_ = 0;
    }

    resultMonitorRunning_ = true;
    resultMonitorThread_ = std::make_unique<std::thread>(&AlgoManagerImpl::ResultMonitorLoop, this);
}

void AlgoManagerImpl::StopResultMonitor()
{
    if (!resultMonitorRunning_) {
        return;
    }

    resultMonitorRunning_ = false;
    if (resultMonitorThread_ && resultMonitorThread_->joinable()) {
        resultMonitorThread_->join();
    }
    resultMonitorThread_.reset();

    std::lock_guard<std::mutex> lock(resultStateMutex_);
    pendingEmptyNotification_ = false;
    lastResultTimestampMs_ = 0;
}

void AlgoManagerImpl::ResultMonitorLoop()
{
    while (resultMonitorRunning_) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));

        bool shouldDispatch = false;
        uint64_t timestampMs = 0;

        {
            std::lock_guard<std::mutex> lock(resultStateMutex_);
            if (pendingEmptyNotification_ && lastResultTimestampMs_ > 0) {
                uint64_t now = GetCurrentTimeMs();
                if (now - lastResultTimestampMs_ >= RESULT_CLEAR_DELAY_MS) {
                    pendingEmptyNotification_ = false;
                    lastResultTimestampMs_ = now;
                    timestampMs = now;
                    shouldDispatch = true;
                }
            }
        }

        if (shouldDispatch) {
            DispatchEmptyResult(timestampMs);
        }
    }
}

void AlgoManagerImpl::DispatchEmptyResult(uint64_t timestampMs)
{
    IAlgoManager::ResultCallback callback;
    {
        std::lock_guard<std::mutex> lock(resultCallbackMutex_);
        callback = resultCallback_;
    }

    if (!callback) {
        return;
    }

    nlohmann::json jsonResult;
    jsonResult["algorithm_type"] = static_cast<int>(ALGO_TYPE_INVALID);
    jsonResult["algorithm_name"] = AlgoTypeToString(ALGO_TYPE_INVALID);
    jsonResult["timestamp"] = timestampMs;
    jsonResult["frame_id"] = 0U;
    jsonResult["object_count"] = 0;
    jsonResult["objects"] = nlohmann::json::array();

    EL_DEBUG("Dispatching empty algorithm result to clear bounding boxes");

    try {
        callback(jsonResult);
    } catch (const std::exception &e) {
        EL_ERROR("Exception in empty result callback: {}", e.what());
    }
}

void AlgoManagerImpl::OnFaceBestEvent(const nlohmann::json &event)
{
    // 组装一次性的结果 JSON（仅包含 face_best_event，用于外发通知）
    nlohmann::json jsonResult;
    jsonResult["algorithm_type"] = static_cast<int>(ALGO_TYPE_FACE_DET);
    jsonResult["algorithm_name"] = AlgoTypeToString(ALGO_TYPE_FACE_DET);
    jsonResult["timestamp"] = event.value("timestamp", GetCurrentTimeMs());
    jsonResult["frame_id"] = 0U;
    jsonResult["object_count"] = 0;
    jsonResult["objects"] = nlohmann::json::array();
    jsonResult["face_best_event"] = event;

    IAlgoManager::ResultCallback cb;
    {
        std::lock_guard<std::mutex> lock(resultCallbackMutex_);
        cb = resultCallback_;
    }
    if (cb) {
        try {
            cb(jsonResult);
        } catch (const std::exception &e) {
            EL_ERROR("Exception while dispatching face_best_event: {}", e.what());
        }
    }
}

void AlgoManagerImpl::NotifyStatusChange(const std::string &instanceId,
                                         AlgoStatus oldStatus,
                                         AlgoStatus newStatus,
                                         const std::string &message)
{
    EL_INFO("Algorithm instance {} status changed: {} -> {}, message: {}", instanceId, static_cast<int>(oldStatus),
            static_cast<int>(newStatus), message);
}

void AlgoManagerImpl::UpdateAlgoStatus(const std::string &instanceId, AlgoStatus newStatus)
{
    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    auto it = algoInstances_.find(instanceId);
    if (it != algoInstances_.end()) {
        AlgoStatus oldStatus = it->second->status;
        it->second->status = newStatus;
        NotifyStatusChange(instanceId, oldStatus, newStatus, "");
    }
}

std::string AlgoManagerImpl::GetCurrentTimeString()
{
    auto now = std::chrono::system_clock::now();
    auto time_t = std::chrono::system_clock::to_time_t(now);
    auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;

    std::stringstream ss;
    ss << std::put_time(std::localtime(&time_t), "%Y-%m-%d %H:%M:%S");
    ss << '.' << std::setfill('0') << std::setw(3) << ms.count();

    return ss.str();
}

uint64_t AlgoManagerImpl::GetCurrentTimeMs()
{
    auto now = std::chrono::system_clock::now();
    auto duration = now.time_since_epoch();
    return std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
}

std::string AlgoManagerImpl::GenerateInstanceId(AlgoType algoType, const std::string &configName)
{
    return AlgoTypeToString(algoType) + "_" + configName + "_" + std::to_string(GetCurrentTimeMs());
}

bool AlgoManagerImpl::StartAlgoInstance(const std::string &instanceId, AlgoType algoType, const nlohmann::json &config)
{
    if (algoType == ALGO_TYPE_INVALID) {
        EL_ERROR("Invalid algorithm type for instance: {}", instanceId);
        return false;
    }

    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    // 检查实例ID是否已经存在
    auto it = algoInstances_.find(instanceId);
    if (it != algoInstances_.end() && it->second->status == AlgoStatus::RUNNING) {
        EL_WARN("Algorithm instance {} is already running", instanceId);
        return true;
    }

    // 创建算法实例
    auto instance = std::make_unique<AlgoInstance>();
    instance->instanceId = instanceId;
    instance->algoType = algoType;
    instance->config = config;
    instance->configName = config.value("type", "");

    // 从配置加载HAL配置
    HAL_ALGO_CONFIG_S halConfig = {};
    if (!LoadAlgoConfigFromFile(instance->configName, config, halConfig)) {
        EL_ERROR("Failed to load algorithm config for instance: {}", instanceId);
        return false;
    }

    // 启动HAL算法
    instance->status = AlgoStatus::INITIALIZING;

    // 记录用于归一化的输入尺寸
    algoInputWidth_.store(halConfig.u32Width);
    algoInputHeight_.store(halConfig.u32Height);

    // 如果是YOLO算法，加载类别标签配置
    if (algoType == ALGO_TYPE_YOLOV8_DET) {
        // 从配置管理器获取类别标签配置
        auto modelConfig = Common::ConfigManager::GetInstance().GetConfig("/model_manager");
        if (!modelConfig.is_null() && modelConfig.contains("yolov8") &&
            modelConfig["yolov8"].contains("class_labels")) {
            UpdateYoloClassLabels(modelConfig["yolov8"]["class_labels"]);
        } else {
            // 如果配置不存在,传递空JSON数组,将使用默认COCO标签
            UpdateYoloClassLabels(nlohmann::json::array());
        }
    }

    // 模型路径随配置结构透传给HAL，无需单独接口

    int ret = Hal_Algo_Start(&halConfig);
    if (ret != 0) {
        EL_ERROR("Failed to start HAL algorithm for instance: {}, ret: {}", instanceId, ret);
        instance->status = AlgoStatus::ERROR;
        return false;
    }

    // 更新实例状态
    instance->status = AlgoStatus::RUNNING;
    instance->initialized = true;
    instance->frameCounter = 0;
    instance->lastResultTime = GetCurrentTimeMs();
    instance->confidenceThreshold = config.value("confidenceThreshold", 0.5f);

    algoInstances_[instanceId] = std::move(instance);

    EL_INFO("Algorithm instance {} started successfully", instanceId);

    return true;
}

bool AlgoManagerImpl::StopAlgoInstance(const std::string &instanceId)
{
    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    auto it = algoInstances_.find(instanceId);
    if (it == algoInstances_.end()) {
        EL_WARN("Algorithm instance {} not found", instanceId);
        return false;
    }

    if (it->second->status != AlgoStatus::RUNNING) {
        EL_WARN("Algorithm instance {} is not running", instanceId);
        return true;
    }

    // 停止HAL算法
    it->second->status = AlgoStatus::STOPPING;

    HAL_ALGO_CONFIG_S halConfig = {};
    halConfig.enType = it->second->algoType;
    int ret = Hal_Algo_Stop(&halConfig);
    if (ret != 0) {
        EL_ERROR("Failed to stop HAL algorithm for instance: {}, ret: {}", instanceId, ret);
        it->second->status = AlgoStatus::ERROR;
        return false;
    }

    // 移除实例
    algoInstances_.erase(it);

    EL_INFO("Algorithm instance {} stopped successfully", instanceId);

    return true;
}

AlgoStatus AlgoManagerImpl::GetAlgoInstanceStatus(const std::string &instanceId) const
{
    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    auto it = algoInstances_.find(instanceId);
    if (it == algoInstances_.end()) {
        return AlgoStatus::IDLE;
    }

    return it->second->status;
}

std::vector<std::string> AlgoManagerImpl::GetRunningInstances(AlgoType algoType) const
{
    std::lock_guard<std::mutex> lock(algoInstancesMutex_);

    std::vector<std::string> instances;
    for (const auto &pair : algoInstances_) {
        if ((algoType == ALGO_TYPE_INVALID || pair.second->algoType == algoType) &&
            pair.second->status == AlgoStatus::RUNNING) {
            instances.push_back(pair.first);
        }
    }

    return instances;
}

void AlgoManagerImpl::UpdateYoloClassLabels(const nlohmann::json& labelsConfig)
{
    try {
        // 验证配置格式
        if (!labelsConfig.is_array()) {
            EL_WARN("Invalid YOLO class_labels configuration format, expected array, got: {}",
                    labelsConfig.type_name());
            return;
        }

        // 转换JSON数组为C风格字符串数组
        std::vector<std::string> labelStrings;
        std::vector<const char *> labelPtrs;

        for (const auto &label : labelsConfig) {
            if (label.is_string()) {
                labelStrings.push_back(label.get<std::string>());
            } else {
                // 如果不是字符串,使用空字符串
                labelStrings.push_back("");
            }
        }

        // 准备C风格指针数组
        for (const auto &str : labelStrings) {
            labelPtrs.push_back(str.c_str());
        }

        // 调用HAL接口热更新类别标签
        if (!labelPtrs.empty()) {
            int ret = Hal_Algo_SetYoloClassLabels(labelPtrs.data(), labelPtrs.size());
            if (ret == 0) {
                EL_INFO("Successfully hot-updated {} YOLO class labels", labelPtrs.size());
            } else {
                EL_ERROR("Failed to hot-update YOLO class labels, ret: {}", ret);
            }
        } else {
            EL_INFO("YOLO class_labels is empty, will use default COCO labels");
            // 传递空标签会让HAL层使用默认标签
            Hal_Algo_SetYoloClassLabels(nullptr, 0);
        }

    } catch (const std::exception &e) {
        EL_ERROR("Exception while updating YOLO class labels: {}", e.what());
    }
}

} // namespace Algo
} // namespace El
